package com.cysd.ewmxns.application

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.StrictMode
import android.util.Log
import androidx.lifecycle.ProcessLifecycleOwner
import com.cszy.ewmxns.common.AppLifecycleTracker
import com.cysd.ewmxns.utils.AppUtil

import com.hlyj.http.base.tool.lib_hlyj_base.BaseApplication
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.listener.IChannelProvider
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.utils.OverlayViewUtils
import com.kongzue.dialogx.DialogX

import com.tencent.mmkv.MMKV
import org.litepal.LitePal

class MyApplication: BaseApplication(),Application.ActivityLifecycleCallbacks, IChannelProvider {
    override fun onCreate() {
        super.onCreate()
        LitePal.initialize(this)
        registerActivityLifecycleCallbacks(this)
        restartSplashListener()//热启动
        DialogX.init(this)
        MMKV.initialize(this)
        var session = BaseModuleSpUtils.getInstance().getInt(Constants.SESSIONID,0);
        session+=1;
        BaseModuleSpUtils.getInstance().putInt(Constants.SESSIONID,session);

    }

    private fun  restartSplashListener() {
        // 注册生命周期监听
        ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleTracker)
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {
        val rootView = activity.window.decorView.rootView
        rootView.viewTreeObserver.addOnWindowFocusChangeListener { hasFocus ->
            if (hasFocus && !activity.isFinishing && !activity.isDestroyed) {
                // 如果 Activity 不属于目标包 且 不是 HtmlActivity，才显示弹窗
                if (!OverlayViewUtils.isTargetPackageActivity(activity)) {
                    var privacyId= BaseModuleSpUtils.getInstance().getString(Constants.PRIVACYID)
                    //  Log.e("onActivityResumed", "onActivityResumed: $privacyId")
                    //OverlayViewUtils.removeCustomOverlay()
                    OverlayViewUtils.showCustomOverlay(activity, privacyId)
                }
            }
        }
    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        OverlayViewUtils.removeCustomOverlay()
    }

    override fun getChannelId(): String {
        return AppUtil.getChannel()
    }


}